package com.sanploy.server.okhttp;

import okhttp3.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/6/19.
 */
public class OKhttpUtil {
    private static final OkHttpClient client = new OkHttpClient();

    public static String sendGetWithParam(String url,Map<String,String> map) throws IOException {
        StringBuffer stringBuffer = new StringBuffer();

        stringBuffer.append(""); //获取get参数
        if (map==null || map.size() >0){
            stringBuffer.append("?");
            map.forEach((key,value)->{
                stringBuffer.append(key);
                stringBuffer.append("=");
                stringBuffer.append(value);
                stringBuffer.append("&");
            });
            stringBuffer.deleteCharAt(stringBuffer.length()-1);
        }

        Request request = new Request.Builder()
                .url(url+stringBuffer.toString())
                .get()
                .build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
        return response.body().string();
    }



    public static String sendGet(String url) throws IOException {

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
        return response.body().string();
    }

    public static String sendPost(String url, Map<String,String> params){

        RequestBody formBody = new FormBody.Builder()
                .add("search", "Jurassic Park")
                .build();

        Request request = new Request.Builder()
                .url("http://fed.sanploy.cn:8099/news/page")
                .post(formBody)
                .build();
        return "";
    }
}
